<template>
  <div class="internal-production-container">
    <el-container>
      <el-header class="search-header">
        <div class="page-title">内部生产</div>
        <div class="header-content">
          <div class="action-buttons">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
            <el-button :icon="Download" @click="handleExport">导出</el-button>
          </div>
          <el-form :inline="true" :model="query" class="search-form">
            <el-form-item class="search-input">
              <el-input 
                v-model="query.productionSubject" 
                placeholder="请输入关键词" 
                clearable 
                @keyup.enter="onSubmit"
                style="width: 300px;">
                <template #append>
                  <el-button @click="onSubmit" :icon="Search"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main class="data-main">
        <el-table 
          :data="tableData" 
          class="data-table" 
          :border="true" 
          :stripe="true"
          v-loading="loading">
          <el-table-column type="index" label="序号" width="80px" align="center">
            <template #default="scope">
              {{ (page.PageIndex - 1) * page.PageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="productionOrderNo" label="生产单号" width="140px" align="center"/>
          <el-table-column prop="productionSubject" label="生产主题" min-width="150px"/>
          <el-table-column prop="documentDate" label="截止日期" width="120px" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.documentDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="物品概要" min-width="200px">
            <template #default="scope">
              <div v-if="scope.row.productItems && scope.row.productItems.length > 0" class="product-items">
                <div class="items-summary">
                  <div>物品概要:</div>
                  <div v-for="(item, index) in scope.row.productItems" :key="index" class="item-detail">
                    {{ item.itemName }}: {{ item.quantity }}
                  </div>
                </div>
              </div>
              <div v-else>{{ scope.row.remarks || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="productionType" label="状态" width="100px" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.productionType)" size="small">
                {{ getStatusText(scope.row.productionType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createName" label="发布人" width="100px" align="center"/>
          <el-table-column prop="initiatingDepartment" label="所在部门" width="120px" align="center"/>
          <el-table-column prop="productionDepartment" label="生产部门" width="120px" align="center">
            <template #default="scope">
              {{ scope.row.productionDepartment || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px" align="center" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button link type="info" @click="handleView(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <div class="pagination-info">
            共{{page.totalCount}}项数据
          </div>
          <el-pagination
            class="pagination"
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[5, 10, 20]"
            :background="true"
            layout="sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="page.totalCount"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { getInternalProductionList, deleteInternalProduction } from '@/Https/server';
import { onMounted, ref, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter();

onMounted(() => {
  GetInternalProductionList();
})

//查询条件
const query = reactive({
  productionSubject: ''
})

//分页参数
const page = reactive({
  PageIndex: 1,
  PageSize: 5,
  totalCount: 0,
  pageCount: 0
})

//加载状态
const loading = ref(false);

//侦听器 - 监听分页变化
watch(page, () => {
  GetInternalProductionList();
}, { deep: true })

//查询方法
const onSubmit = () => {
  page.PageIndex = 1; // 重新搜索时回到第一页
  GetInternalProductionList();
}

//加载内部生产数据
const tableData = ref<any>([]);
const GetInternalProductionList = () => {
  loading.value = true;
  const params = {
    ProductionSubject: query.productionSubject,
    PageIndex: page.PageIndex,
    PageSize: page.PageSize
  };
  
  getInternalProductionList(params).then((res: any) => {
    console.log('API返回的数据:', res);
    tableData.value = res.pageData || [];
    page.totalCount = res.pageCount ? res.pageCount * page.PageSize : 0;
    page.pageCount = res.pageCount || 0;
    loading.value = false;
  }).catch((error) => {
    console.error('获取内部生产列表失败:', error);
    ElMessage.error('获取内部生产列表失败');
    loading.value = false;
  });
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 获取状态类型
const getStatusType = (productionType: string) => {
  switch(productionType) {
    case '批量生产':
      return 'primary';
    case '定制生产':
      return 'success';
    case '试验生产':
      return 'warning';
    case '紧急生产':
      return 'danger';
    default:
      return 'info';
  }
}

// 获取状态文本
const getStatusText = (productionType: string) => {
  return productionType || '未知';
}

// 编辑
const handleEdit = (row: any) => {
  if (!row.id) {
    ElMessage.error('生产ID不存在，无法编辑');
    return;
  }
  router.push(`/internal-production/edit/${row.id}`);
}


// 查看详情
const handleView = (row: any) => {
  if (!row.id) {
    ElMessage.error('生产ID不存在，无法查看详情');
    return;
  }
  router.push(`/internal-production/view/${row.id}`);
}

// 删除内部生产
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除内部生产"${row.productionSubject}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      loading.value = true;
      
      // 创建FormData传递productionId参数
      const formData = new FormData();
      formData.append('productionId', row.id.toString());
      
      const result: any = await deleteInternalProduction(formData);
      
      if (result && result.code === 200) {
        ElMessage.success(result.message || '删除成功');
        GetInternalProductionList(); // 刷新列表
      } else {
        ElMessage.error(result?.message || '删除失败');
      }
    } catch (error: any) {
      console.error('删除内部生产失败:', error);
      ElMessage.error(error?.message || '删除失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 新增
const handleAdd = () => {
  router.push('/internal-production/add');
}

// 导出
const handleExport = () => {
  ElMessage.info('导出内部生产数据');
}
</script>

<style scoped>
.internal-production-container {
  background: #f5f5f5;
  min-height: 100vh;
}

.search-header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 80px !important;
  flex-direction: column;
  align-items: flex-start;
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-form {
  display: flex;
  align-items: center;
  margin: 0;
}

.search-input {
  margin-right: 0;
}

.data-main {
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
}

.product-items {
  text-align: left;
}

.items-summary {
  font-size: 12px;
  line-height: 1.4;
}

.item-detail {
  color: #666;
  margin-left: 10px;
}



.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-top: 1px solid #e6e6e6;
  margin-top: 20px;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination {
  margin: 0;
}

:deep(.el-button--text) {
  padding: 4px 8px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>